import { Component, Inject, Optional, OnInit, ViewChild, InjectionToken } from '@angular/core';
import { EntityDtoOfInt64, TokenAuthServiceProxy, SFOrderListDto, WaybillDto, SFOrderServiceProxy } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { HttpClient, HttpParams, HttpHeaders, HttpResponse, HttpResponseBase } from '@angular/common/http';
import { baseDirectiveCreate } from '@angular/core/src/render3/instructions';
import { AppConsts } from '@shared/AppConsts';

export const printUrl = new InjectionToken<string>('printUrl');

@Component({
  selector: 'printModal',
  templateUrl: './print-modal.component.html',
  styleUrls: ['./print-modal.component.css']
})
export class PrintModalComponent implements OnInit {
  @ViewChild('printModal') modal: ModalDirective;
  active = false;
  imgData = '';
  orderId = 0;
  private http: HttpClient;

  constructor(
    private _sfOrderServiceProxy: SFOrderServiceProxy,
    @Inject(HttpClient) http: HttpClient, @Optional() @Inject(printUrl) printUrl?: string
  ) {
    this.http = http;
  }

  ngOnInit() {

  }

  show(id: number): void {
    if (!id) {
      this.active = true;
    }
    this._sfOrderServiceProxy.getPrintImg(id)
      .subscribe((ref) => {
        // this.notify.success('操作成功');

        this.imgData = 'data:image/png;base64,' + ref;

        document.getElementById('printImg').setAttribute('src', this.imgData);

        console.log(ref);
        this.modal.show();
        this.orderId = id;
      });

  }
  close(): void {
    this.active = false;
    this.modal.hide();
  }

  onShown(): void {

    document.getElementById('btnPrint').focus();
  }
  print(): void {
    this._sfOrderServiceProxy.getPrintJson(this.orderId)
      .subscribe((ref) => {
        abp.notify.success('操作成功');

        let options_: any = {
          observe: 'response',
          //body: JSON.stringify({ 'json': ref }),
          responseType: 'blob',
          headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'http-equiv': 'Content-Security-Policy',
            'content': 'upgrade-insecure-requests'
          })
        };
        let ss = {
          params: new HttpParams().set('json', ref)
        };
        this.http.post(AppConsts.printUrl, { 'json': ref }, options_).subscribe(data => {
          console.log(data);



        });
      });
  }

  printByLocal(info: WaybillDto[]): void {

    //根据业务需求确定请求地址
    let reqURL = AppConsts.printUrl;
    console.log(reqURL);

    //电子面单顶部是否需要logo
    let topLogo = true; //true 需要logo  false 不需要logo
    if (reqURL.indexOf('V2.0') !== -1 && topLogo) {
      reqURL = reqURL.replace(/V2.0/ig, 'V2.1');
    }

    if (reqURL.indexOf('V3.0') !== -1 && topLogo) {
      reqURL = reqURL.replace(/V3.0/ig, 'V3.1');
    }

    /**
     * 其中127.0.0.1:4040为打印服务部署的地址（端口如未指定，默认为4040）
     * type为模板类型（支持两联、三联，尺寸为100mm*150mm和100mm*210mm，type为poster_100mm150mm和poster_100mm210mm）
     * A5 poster_100mm150mm   A5 poster_100mm210mm
     * output为输出类型,值为print或image，如不传
     * 默认为print（print 表示直接打印，image表示获取图片的BASE64编码字符串）
     * V2.0/V3.0模板顶部是带logo的  V2.1/V3.1顶部不带logo
     * 若有签回单号，则需配置签回单丰密相关配置，即参数rlsInfoDtoList[1]
     */
    console.log('请求地址：' + reqURL);

    console.log('请求参数：' + JSON.stringify(info));


    let options = {
      body: JSON.stringify(info)
    };

    let options_: any = {
      observe: 'response',
      body: JSON.stringify(info),
      responseType: 'blob',
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'http-equiv': 'Content-Security-Policy',
        'content': 'upgrade-insecure-requests'
      })
    };

    console.log(options_);

    //this.http.jsonp(reqURL, 'callback');
    this.http.request('post', reqURL, options_).subscribe(result => {
      console.log(result);
    });
  }
  callback(): void {
    console.log('callback');

  }
  printpage(div: string): void {
    let newstr = document.getElementById(div).innerHTML;
    let oldstr = document.body.innerHTML;
    document.body.innerHTML = newstr;
    window.print();
    document.body.innerHTML = oldstr;
  }
}


